from server.sessionstuff.session import Session
import __builtin__


class SessionManager(object):
    def __init__(self):
        self.sessions = []

    def create_session(self, creator):
        ses = Session(self.get_free_id(), creator)
        self.sessions.append(ses)
        return ses

    def set_session_atk(self, ses_id, player):
        for s in self.sessions:
            if s.ID == ses_id:
                s.attacker = player
                return

    def set_session_def(self, ses_id, player):
        for s in self.sessions:
            if s.ID == ses_id:
                s.defender = player
                return

    def get_session_byid(self, ses_id):
        for s in self.sessions:
            if s.ID == ses_id:
                return s

    def remove_session(self, given_id):
        for s in self.sessions:
            print str(s.ID) + " " + str(given_id)
            if str(s.ID) == str(given_id):
                self.sessions.remove(s)
                print "Session " + str(given_id) + " stopped"
                __builtin__.base.networkmanager.broadcast_gamelist()

    def session_finished(self, given_id):
        for s in self.sessions:
            if str(s.ID) == str(given_id):
                __builtin__.base.networkmanager.send_session_closed(s.attacker.peer)
                __builtin__.base.networkmanager.send_session_closed(s.defender.peer)
                self.sessions.remove(s)
                __builtin__.base.networkmanager.broadcast_gamelist()

    def get_free_id(self):
        free_ses = None
        cur = 0

        while free_ses is None:
            free_ses = cur
            for s in self.sessions:
                if s.ID == cur:
                    cur += 1
                    free_ses = None
                    break

        print "Free Sesion ID: " + str(free_ses)
        return free_ses

    def update(self, dt):
        for s in self.sessions:
            s.update(dt)